﻿<%@ WebHandler Language="C#" Class="ContractMgr" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;

public class ContractMgr : AjaxHandlerBase
{

    override public void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            switch (strOp.ToLower())
            {
                //添加合同
                case "add":
                    Add(context);
                    break;
                case "edit":
                    Edit(context);
                    break;
                case "getlist":
                    GetList(context);
                    break;
                case "getmodel":
                    GetModel(context);
                    break;
                case "changestatus":
                    ChangeStatus(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    /// <summary>
    /// 自定义权限检查
    /// </summary>
    /// <param name="context"></param>
    /// <param name="strMsg"></param>
    /// <returns></returns>
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        if (context.Request["code"] != null)
        {
            switch (context.Request["code"].ToLower())
            {
                case "print":
                    if (CurrentUserInfo.ContainsPermit(Constants.Permit_ContractRepeatPrint))
                    {
                        Chenxin.Lib.Business.Entity.ContractInfo modle = Chenxin.Lib.Business.DAL.ContractInfo.GetModel(new Guid(context.Request["contractId"]));
                        //Chenxin.Lib.Business.Entity.ContractInfo modle = (Chenxin.Lib.Business.Entity.ContractInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Business.Entity.ContractInfo));

                        //插入打印记录
                        Chenxin.Lib.Business.Entity.ContractPrintInfo modlePrint = new Chenxin.Lib.Business.Entity.ContractPrintInfo();
                        modlePrint.ContractPrint_ID = Guid.NewGuid();
                        modlePrint.ContractPrint_Date = DateTime.Now;
                        modlePrint.Contract_Id = modle.Contract_Id;
                        modlePrint.Contract_Code = modle.Contract_Code;
                        modlePrint.User_Code = CurrentUserInfo.UserCode;
                        modlePrint.User_ID = CurrentUserInfo.UserId;
                        modlePrint.User_Name = CurrentUserInfo.UserName;
                        modlePrint.ContractPrint_Reason = "首次打印";
                        Chenxin.Lib.Business.DAL.ContractPrintInfo.Add(modlePrint);

                        //更新合同打印次数及最后打印人信息
                        modle.Contract_PrintCount = 1;
                        modle.Contract_LastPrintDate = modlePrint.ContractPrint_Date;
                        modle.Contract_LastPrintUserId = modlePrint.User_ID;
                        modle.Contract_LastPrintUserName = modlePrint.User_Name;
                        Chenxin.Lib.Business.DAL.ContractInfo.Update(modle);
                        strMsg = "{success:1,msg:'',data:{permit:true}}";
                        return true;
                    }
                    else
                    {
                        strMsg = "{success:1,msg:'',data:{permit:false}}";
                        return true;
                    }
                    break;
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }
    
    private void ChangeStatus(HttpContext context)
    {
        try
        {
            int status = Convert.ToInt32(context.Request["status"]);
            Chenxin.Lib.Business.DAL.ContractInfo.ChangeStatus(new Guid(context.Request["modelid"]), status);


            string msg = status == 0 ? "作废合同操作成功！" : "恢复合同有效操作成功！";
            context.Response.Write(string.Format("{{success:1,msg:'{0}',data:''}}", msg));
        }
        catch (Exception e)
        {
            context.Response.Write(string.Format("{{success:0,msg:'保存失败！原因：{0}',data:''}}", e.Message.Replace("'", "\"")));
        }
    }
    
    private void Edit(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Business.Entity.ContractInfo modle = (Chenxin.Lib.Business.Entity.ContractInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Business.Entity.ContractInfo));

            Chenxin.Lib.Business.DAL.ContractInfo.Update(modle);

            context.Response.Write(string.Format("{{success:1,msg:'保存成功！',data:{{contract_id:'{0}'}}}}", modle.Contract_Id));
        }
        catch (Exception e)
        {
            context.Response.Write(string.Format("{{success:0,msg:'保存失败！原因：{0}',data:''}}", e.Message.Replace("'", "\"")));
        }        
    }
    
    private void GetModel(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Business.Entity.ContractInfo model = Chenxin.Lib.Business.DAL.ContractInfo.GetModel(new Guid(context.Request["modelid"]));
            context.Response.Write(string.Format("{{success:1,msg:'',data:{{model:{0}}}}}", JsonHelp.Convert2Json(model)));
        }
        catch
        {
            context.Response.Write("{success:0,msg:'获取记录信息失败！',data:''}");
        }
    }

    private void GetList(HttpContext context)
    {
        try
        {

            string strWhere = "1=1";
            string order = "Contract_Date desc";

            int pageSize = 10;
            int pageIndex = 1;
            int count = 0;

            if (context.Request["pagesize"] != null)
            {
                pageSize = Convert.ToInt32(context.Request["pagesize"]);
            }
            if (context.Request["pageindex"] != null)
            {
                pageIndex = Convert.ToInt32(context.Request["pageindex"]) + 1;
            }

            if (context.Request["contractcode"] != null)
            {
                strWhere += string.Format(" and Contract_Code like '%{0}%'", context.Request["contractcode"]);
            }

            if (context.Request["contract_type"] != null)
            {
                strWhere += string.Format(" and Contract_Type='{0}'", context.Request["contract_type"]);
            }

            if (context.Request["cityid"] != null)
            {
                strWhere += string.Format(" and CityId='{0}'", context.Request["cityid"]);
            }
            else
            {
                strWhere += string.Format(" and CityId='{0}'", CurrentUserInfo.CityId);
            }

            if (context.Request["companyid"] != null)
            {
                strWhere += string.Format(" and CompanyId='{0}'", context.Request["companyid"]);
            }

            if (context.Request["endtime"] != null && context.Request["starttime"] != null)
            {
                strWhere += string.Format(" and (Contract_Date>'{0}' and Contract_Date<'{1}')", context.Request["endtime"], context.Request["starttime"]);                
            }

            if (context.Request["status"] != null)
            {
                strWhere += string.Format("and Contract_Status={0}", context.Request["status"]); 
            }
            if (context.Request["sort"] != null && context.Request["sort"] != "")
            {
                order = context.Request["sort"];
            }

            DataSet ds = Chenxin.Lib.Business.DAL.ContractInfo.GetList(pageIndex, pageSize, order, strWhere, "*", "*", true);
            count = Convert.ToInt32(ds.Tables[1].Rows[0].ItemArray[0]);
            context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1},strWhere:'{2}'}}}}", count, JsonHelp.Convert2Json(ds.Tables[0]),strWhere.Replace("'","\"")));
            
        }
        catch (Exception e)
        {
            context.Response.Write(string.Format("{{success:0,msg:'加载失败！原因：{0}',data:''}}", e.Message.Replace("'", "\"")));
        }
    }

    private void Add(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Business.Entity.ContractInfo modle = (Chenxin.Lib.Business.Entity.ContractInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.Business.Entity.ContractInfo));

            modle.Contract_Id = Guid.NewGuid();
            modle.Contract_Date = DateTime.Now;
            modle.Contract_Code = Chenxin.Lib.Business.BLL.ContractBaseInfo.GenerateCode(modle.CompanyId, 0);
            modle.Contract_Status = 10;
            Chenxin.Lib.Business.DAL.ContractInfo.Add(modle);

            context.Response.Write(string.Format("{{success:1,msg:'保存成功！',data:{{contract_id:'{0}'}}}}", modle.Contract_Id));
        }
        catch(Exception e)
        {
            context.Response.Write(string.Format("{{success:0,msg:'保存失败！原因：{0}',data:''}}", e.Message.Replace("'", "\"")));
        }
    }

}